import React, { useState } from 'react';
import { ApiService } from '../services/api';
import { DBQueryResult } from '../types/api';
import { API_CONFIG } from '../config';

interface DBSectionProps {
  node: keyof typeof API_CONFIG.NODES;
}

export const DBSection: React.FC<DBSectionProps> = ({ node }) => {
  const [query, setQuery] = useState<string>('');
  const [result, setResult] = useState<DBQueryResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!query) {
      setError('请输入查询语句');
      return;
    }

    try {
      setLoading(true);
      setError(null);
      setResult(null);

      console.log('Executing query:', query);
      const response = await ApiService.queryDB(node, query);
      console.log('DB response:', response);
      
      if (response && response.result) {
        setResult(response.result);
      } else {
        setError(`查询失败: ${response?.message || '查询执行失败'}`);
      }
    } catch (err) {
      setError(`查询数据库失败: ${err instanceof Error ? err.message : '未知错误'}`);
      console.error('Error querying database:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="bg-white shadow rounded-lg p-6">
      <h2 className="text-xl font-semibold mb-4">数据库查询</h2>
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label htmlFor="query" className="block text-sm font-medium text-gray-700">
            查询语句
          </label>
          <textarea
            id="query"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
            rows={4}
            placeholder="请输入查询语句..."
          />
        </div>
        <button
          type="submit"
          disabled={loading}
          className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
        >
          {loading ? '查询中...' : '执行查询'}
        </button>
      </form>

      {error && (
        <div className="mt-4 text-red-500 bg-red-50 p-4 rounded-md">
          <p className="font-medium">错误:</p>
          <p>{error}</p>
        </div>
      )}

      {result && (
        <div className="mt-4">
          <h3 className="font-medium">查询结果</h3>
          <pre className="mt-2 p-4 bg-gray-50 rounded-md overflow-auto">
            {JSON.stringify(result, null, 2)}
          </pre>
        </div>
      )}
    </div>
  );
}; 